﻿using CommunityToolkit.Mvvm.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using StickyNote.Core;
using StickyNote.Services;
using StickyNote.ViewModels;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows;

namespace StickyNote
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static Mutex? AppMutex;

        protected override void OnStartup(StartupEventArgs e)
        {
            AppMutex = new Mutex(true, "StickyNote", out var createdNew);

            if (!createdNew)
            {
                var current = Process.GetCurrentProcess();

                foreach (var process in Process.GetProcessesByName(current.ProcessName))
                {
                    if (process.Id != current.Id)
                    {
                        process.Kill();
                        break;
                    }
                }
            }

            ShutdownMode = ShutdownMode.OnMainWindowClose;
            Ioc.Default.ConfigureServices(
               new ServiceCollection()
               .AddTransient<MainWindowViewModel>()
               .AddTransient<NoteWindowViewModel>()
               .AddSingleton<NoteService>()
               .AddSingleton<JotService>()
               .BuildServiceProvider());
            base.OnStartup(e);
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
            NoteService noteService = Ioc.Default.GetRequiredService<NoteService>();
            IniHelper.SetValue(E_Sections.业务.ToString(), E_Keys.便签.ToString(), string.Join(",", noteService.NoteWindows.Select(p => p.Name)));
        }
    }
}
